package com.xmut.mall.order.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xmut.mall.order.feign.WareFeignService;
import com.xmut.mall.order.service.OrderService;
import com.xmut.mall.order.utils.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
@Slf4j
public class CancelOrderListener {
    @Autowired
    private OrderService orderService;

    @Bean
    public void OrderUnLock() {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("cancelgroup");
        try {
            consumer.setNamesrvAddr("192.168.253.128:9876");
            consumer.subscribe("CancelOrderTopic", "*");
            consumer.registerMessageListener(new MessageListenerConcurrently() {
                public ConsumeConcurrentlyStatus consumeMessage(
                        List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                    Map<String, Object> param = new HashMap<>();
                    for (MessageExt msg : msgs) {
                        System.out.println("消费者获取数据:" + msg.getMsgId() + "==>" + new String(msg.getBody()));
                        param = JSON.parseObject(new String(msg.getBody(), StandardCharsets.UTF_8), new TypeReference<Map<String, Object>>() {
                        });
                        try {
                            orderService.cancelOrderReasonTimeout(param);
                        } catch (Exception e) {
                            System.out.println("取消订单错误");
                            e.printStackTrace();
                        }
                    }

                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }
}
